package source

import (
	"crypto/md5"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"net/url"
	"strings"
)

const (
	YdAppKey  = "5f1ea5598319d232"
	YdScret   = "L7oHzhzf1IpIsyhGnY314Et4qJiCXDGb"
	YdBaseUrl = "http://openapi.youdao.com/api"
)

type resultBase struct { // 有道词典-基本词典,查词时才有
	Phonetic   string //拼音
	UkPhonetic string //英式音标
	UsPhonetic string //美式音标
	UkSpeech   string //英式发音
	UsSpeech   string //美式发音
	Explains   []string
}

type resultWeb struct { // 有道词典-网络释义，该结果不一定存在
	Key   string
	Value []string
}

type Ydrespose struct {
	ErrorCode   string
	Query       string
	Translation []string
	Basic       resultBase
	Web         []resultWeb
}

// 有道源翻译
func TranslateYoudao(q, fromType string) []string {
	var wordMeans []string
	h := md5.New()
	salt := GetRandomSalt()
	h.Write([]byte((YdAppKey + q + salt + YdScret)))

	//根据中英文判断返回值
	var toResult string
	if fromType != "zh" {
		toResult = "zh-CHS"
	} else {
		toResult = "en"
	}

	hexSting := hex.EncodeToString(h.Sum(nil))
	sign := strings.ToUpper(hexSting)
	queryWord := url.QueryEscape(q)
	getUrls := YdBaseUrl + "?q=" + queryWord + "&from=auto&to=" + toResult + "&appKey=" + YdAppKey + "&salt=" + salt + "&sign=" + sign
	body, err := GetJson(getUrls)
	if err != nil {
		fmt.Println("返回结果出错", err)
	}

	var r Ydrespose
	if err2 := json.Unmarshal(body, &r); err2 != nil {
		fmt.Println("返回结果出错", err2)
	}

	explains := r.Basic.Explains
	if len(explains) != 0 {
		for i := 0; i < len(explains); i++ {
			wordMeans = append(wordMeans, explains[i])
		}
	} else {
		translation := r.Translation
		for i := 0; i < len(translation); i++ {
			wordMeans = append(wordMeans, translation[i])
		}
	}

	return wordMeans
}
